/*
 * @Author: liuyonghu
 * @Date: 2021-12-24 23:42:29
 * @LastEditTime: 2021-12-24 23:47:08
 * @LastEditors: liuyonghu
 * @Description:
 * @FilePath: /learn-three-js/21-1223/index.js
 */

let loadingFlag = 0,
  renderer,
  group,
  controls,
  scene,
  camera,
  audio;
function start() {
  const modal = document.querySelector('#modal');
  modal.style.display = 'none';
  // 播放缓冲区中的音频数据
  audio.play(); //play播放、stop停止、pause暂停
}
function render() {
  controls.enableZoom = false;
  controls.enablePan = false;
  controls.update();
  group.children.forEach((sprite) => {
    // 雨滴的y坐标每次减1
    sprite.position.y -= 0.001;
    if (sprite.position.y <= -0.5) {
      // 如果雨滴落到地面，重置y，从新下落
      sprite.position.y = Math.random() * 1 + 1.5;
    }
  });
  renderer.render(scene, camera);
}

function animate() {
  requestAnimationFrame(animate);
  render();
}

function loadingAdd() {
  loadingFlag += 1;
  if (loadingFlag >= 5) {
    const loading = document.querySelector('#loading');
    loading.style.display = 'none';

    const start = document.querySelector('#start');
    start.style.display = 'block';

    animate();
  }
}
// import * as THREE from '../threejs/three.module.js';
import('../threejs/three.module.js').then(async (module) => {
  window.THREE = Object.assign({}, module);
  await import('../threejs/orbitControls.js');
  await import('../threejs/GLTFLoader.js');
  await import('../threejs/TextGeometry.js');
  import('../threejs/FontLoader.js').then((module) => {
    window.FontLoader = module.FontLoader;
    import('../threejs/TextGeometry.js').then((module) => {
      window.TextGeometry = module.TextGeometry;
      afterload();
    });
  });
});

function afterload() {
  // 非位置音频可用于不考虑位置的背景音乐
  // 创建一个监听者
  var listener = new THREE.AudioListener();
  // camera.add( listener );
  // 创建一个非位置音频对象  用来控制播放
  // 加载音频文件，返回一个音频缓冲区对象作为回调函数参数

  audio = new THREE.Audio(listener);
  // 创建一个音频加载器对象
  var audioLoader = new THREE.AudioLoader();
  // create a render
  renderer = new THREE.WebGLRenderer({ antialias: true });

  // create a scene, that will hold all our elements such as objects, cameras and lights.
  scene = new THREE.Scene();
  // create a camera, which defines where we're looking at
  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  function init() {
    audioLoader.load('../audios/铃儿响叮当.mp3', function (AudioBuffer) {
      // console.log(AudioBuffer)
      // 音频缓冲区对象关联到音频对象audio
      audio.setBuffer(AudioBuffer);
      audio.setLoop(true); //是否循环
      audio.setVolume(0.5); //音量
      loadingAdd();
    });

    // tell the camera where to look
    camera.position.set(0, 0, 5);
    //  render  set the size
    const sizes = {
      width: window.innerWidth,
      height: window.innerHeight,
    };
    renderer.setSize(sizes.width, sizes.height);
    renderer.setClearColor('#9ec6ff', 1);

    //点光源
    var point = new THREE.PointLight('#fff');
    point.position.set(20, 10, 10); //点光源位置
    scene.add(point); //点光源添加到场景中

    var point1 = new THREE.PointLight('#fff');
    point1.position.set(0, 10, 10); //点光源位置
    scene.add(point1); //点光源添加到场景中

    //环境光
    var ambient = new THREE.AmbientLight('#dfdfdf');
    scene.add(ambient);

    // add the output of the render function to the HTML
    document.body.appendChild(renderer.domElement);
    // 文字

    const font_loader = new FontLoader();

    const font = font_loader.load(
      '../fonts-json/FZDongQiChangXingShuS_Regular.json',
      function (font) {
        var font_geometry = new TextGeometry('勇虎祝您圣诞节快乐！', {
          font: font,
          size: 0.3,
          height: 0.05,
          curveSegments: 12,
          bevelEnabled: false,
          bevelThickness: 10,
          bevelSize: 8,
          bevelSegments: 5,
        });
        const font_material = new THREE.MeshToonMaterial({
          color: '#ff2b2b',
        });
        const font_mesh = new THREE.Mesh(font_geometry, font_material);
        font_mesh.position.set(-1, -1, 2.5);
        scene.add(font_mesh);
        loadingAdd();
      }
    );

    // 地面
    const land_gemetry = new THREE.CylinderBufferGeometry(20, 20, 5, 32);
    const land_material = new THREE.MeshLambertMaterial({
      color: '#fff',
    });
    const land_mesh = new THREE.Mesh(land_gemetry, land_material);
    // land_mesh.rotation.set(Math.PI / 4, 0, 0);
    land_mesh.position.set(0, -4, 0);

    scene.add(land_mesh);
    // 雪花
    // 创建精灵材质对象SpriteMaterial

    group = new THREE.Group();
    for (let index = 0; index < 3000; index++) {
      const spriteGeometry = new THREE.SphereGeometry(0.01, 32, 16);
      const material = new THREE.MeshBasicMaterial({ color: '#fff' });
      const sprite = new THREE.Mesh(spriteGeometry, material);
      sprite.position.set(
        5.5 - Math.random() * 10,
        Math.random() * 6 - 0.5,
        5.5 - Math.random() * 10
      );

      group.add(sprite);
    }
    scene.add(group);
    var loader = new THREE.GLTFLoader();
    //
    controls = new THREE.OrbitControls(camera, renderer.domElement); //创建控件对象
    // 自动旋转
    controls.autoRotate = true;

    loader.load(
      '../modols/christmas_2022/scene.gltf',
      function (gltf) {
        //   console.log(gltf);
        //   console.log(gltf.scene.position);
        gltf.scene.position.set(1, -1, 0);
        scene.add(gltf.scene);

        controls.minPolarAngle = 0;
        controls.maxPolarAngle = Math.PI / 2;
        controls.minZoom = 1;

        loadingAdd();
        // 注意开发中不要同时使用requestAnimationFrame()或controls.addEventListener('change', render)调用同一个函数，这样会冲突

        // controls.addEventListener('change', render); //监听鼠标、键盘事件
      },
      undefined,
      function (error) {
        console.error(error);
      }
    );

    loader.load(
      '../modols/snowman/scene.gltf',
      function (gltf) {
        gltf.scene.position.set(-1, -1.5, 0);
        const scale = 0.004;
        gltf.scene.scale.set(scale, scale, scale);
        scene.add(gltf.scene);
        loadingAdd();
      },
      undefined,
      function (error) {
        console.error(error);
      }
    );

    loader.load(
      '../modols/fir_tree_set_with_snow/scene.gltf',
      function (gltf) {
        gltf.scene.position.set(27, -1, 45);
        const scale = 0.015;
        gltf.scene.scale.set(scale, scale, scale);
        scene.add(gltf.scene);
        loadingAdd();
      },
      undefined,
      function (error) {
        console.error(error);
      }
    );
  }
  init();
  // 调整
  window.onresize = () => {
    const sizes = {
      width: window.innerWidth,
      height: window.innerHeight,
    };
    // 重新设置相机宽高比例
    camera.aspect = window.innerWidth / window.innerHeight;
    // 更新相机投影矩阵
    camera.updateProjectionMatrix();
    // 重新设置渲染器渲染范围
    renderer.setSize(sizes.width, sizes.height);

    // renderer.render(scene, camera);
  };
}
